package org.metasketch.editor.toolbox;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;

import org.metasketch.model.CommonIdentified;
import org.metasketch.reflection.RefUtil;

public class SimpleRelation extends BaseRelation {

	RefUtil util = new RefUtil();

	String childFieldname;
	String parentFieldname;

	String script;

	public SimpleRelation() {

	}

	public SimpleRelation(Class childType, Class parentType,
			String childFieldname, String parentFieldname) {
		super(childType, parentType);
		this.childFieldname = childFieldname;
		this.parentFieldname = parentFieldname;

	}

	public boolean isCompatible(Class argChildType, Class argParentType) {
		if (argChildType.equals(childType) && argParentType.equals(parentType))
			return true;

		return false;
	}

	public void setup(CommonIdentified semantic, CommonIdentified parentSemantic)
			throws Throwable {

		if (childFieldname != null) {
			util.setValue(semantic, childFieldname, parentSemantic);
		}

		if (parentFieldname != null) {
			util.setValue(parentSemantic, parentFieldname, semantic);
		}

		if (script != null) {
			Binding binding = new Binding();
			binding.setVariable("child", semantic);
			// binding.setVariable("label", label);
			binding.setVariable("parent", parentSemantic);
			GroovyShell shell = new GroovyShell(binding);

			shell.evaluate(script);
		}

	}

	public String getChildFieldname() {
		return childFieldname;
	}

	public void setChildFieldname(String childFieldname) {
		this.childFieldname = childFieldname;
	}

	public String getParentFieldname() {
		return parentFieldname;
	}

	public void setParentFieldname(String parentFieldname) {
		this.parentFieldname = parentFieldname;
	}

	public String getScript() {
		return script;
	}

	public void setScript(String script) {
		this.script = script;
	}

}
